package com.example.vertification.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.vertification.entity.*;
import com.example.vertification.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@Api(value = "订单管理", tags = "订单管理")
public class OrderController {

    private final OrderService orderService;
    private final UserService userService;
    private final UserStationService userStationService;
    private final UserShopService userShopService;
    private final UserAddressService userAddressService;

    @Autowired
    public OrderController(UserService userService, OrderService orderService,UserShopService userShopService, UserStationService userStationService,UserAddressService userAddressService) {
        this.userService = userService;
        this.orderService = orderService;
        this.userStationService = userStationService;
        this.userShopService = userShopService;
        this.userAddressService=userAddressService;
    }

    @PostMapping("/create_order")
    @ApiOperation(value = "传入类型为对象,内含{token,shopID,tradewayID,typeID,amount,stationID")
    public ResponseEntity<?> create_order(@RequestBody String body) throws IOException {
        JSONObject obj_get = JSONUtil.parseObj(body);
        String token = obj_get.getStr("token");
        long ShopID = obj_get.getLong("shopID");
        int tradewayID = obj_get.getInt("tradewayID");
        int typeID = obj_get.getInt("typeID");
        int amount = obj_get.getInt("amount");
        int stationID = obj_get.getInt("stationID");


        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        UserShop us = userShopService.getEntityByUid(ShopID);
        if(us==null){
            return ResponseEntity.ok("该店铺不存在!");
        }
        if(us.getType() == UserShop.TradeType.OnlyYourself && tradewayID == 1){
            return ResponseEntity.ok("抱歉,企业不上门收购秸秆!");
        }
        if(us.getType() == UserShop.TradeType.OnlySelf && tradewayID == 0){
            return ResponseEntity.ok("抱歉,当前企业只接受自行上门回收的方式!");
        }
        UserStation usa = userStationService.getEntityByUid(ShopID);
        if(usa==null){
            return ResponseEntity.ok("该企业暂未开设站点!");
        }
        JSONArray stations = new JSONArray();
        if(usa.getStations().equalsIgnoreCase("") == false){
            stations = JSONUtil.parseArray(usa.getStations());
        }
        if(stations.size()<stationID){
            return ResponseEntity.ok("传入的站点ID超过了该店铺的最大上线!");
        }


        JSONArray buy_list = JSONUtil.parseArray(us.getBuys());
        if(buy_list.size()==0){
            return ResponseEntity.ok("该店铺暂未收购商品!");
        }
        JSONObject buy_tem_obj = (JSONObject) buy_list.get(typeID);
        if(buy_tem_obj==null){
            return ResponseEntity.ok("该商品不存在!");
        }
        long max_amount = buy_tem_obj.getLong("amount");
        if(amount>max_amount){
            return ResponseEntity.ok("超出了该店铺当前商品的最大数量,无法回收!");
        }


        Order order = new Order();
        //生成随机订单字符串num
        order.setOrderNumber(order.generateOrderNumber());
        order.setProductBuyerUid(ShopID);
        order.setProductSellerUid(u.getUid());
        order.setProductName(buy_tem_obj.getStr("name"));
        order.setProduct_price(buy_tem_obj.getLong("price"));
        order.setProduct_amount(amount);
        order.setTrade_type(tradewayID);


        //0自送上门
        //1企业上门
        if(tradewayID==0){
            UserAddress u_address = userAddressService.getEntityByUid(u.getUid());
            if(u_address==null){
                return ResponseEntity.ok("您还未设置第一条默认上门地址,无法回收!");
            }
            String address_list = u_address.getAddresses();
            if(address_list.equalsIgnoreCase("")){
                return ResponseEntity.ok("你暂未设置默认上门地址,无法回收!");
            }
            JSONArray address_list_json = JSONUtil.parseArray(address_list);
            JSONObject address_list_default = (JSONObject)address_list_json.get(0);
            order.setFrom_where(address_list_default.getStr("address"));


            JSONObject obj = JSONUtil.parseObj(stations.get(stationID));

            order.setTo_where(obj.getStr("address"));
            order.setStation_id(stationID);
            order.setTrade_type(0);
        }else{


            UserAddress u_address = userAddressService.getEntityByUid(ShopID);
            if(u_address==null){
                return ResponseEntity.ok("该企业暂未设置第一条默认上门地址,无法回收!");
            }
            String address_list = u_address.getAddresses();
            if(address_list.equalsIgnoreCase("")){
                return ResponseEntity.ok("该企业暂未设置第一条默认上门地址,无法回收!");
            }
            JSONArray address_list_json = JSONUtil.parseArray(address_list);
            JSONObject address_list_default = (JSONObject)address_list_json.get(0);
            order.setTo_where(address_list_default.getStr("address"));


            UserAddress u_address2 = userAddressService.getEntityByUid(u.getUid());
            if(u_address2==null){
                return ResponseEntity.ok("该用户暂未设置第一条收货地址,无法回收!");
            }
            String user_stations = userStationService.getEntityByUid(ShopID).getStations();

            if(user_stations.equalsIgnoreCase("")){
                return ResponseEntity.ok("该用户暂未设置第一条站点地址,无法回收!");
            }
            JSONArray qy_stations = JSONUtil.parseArray(user_stations);

            JSONObject address_list_default2 = (JSONObject)qy_stations.get(stationID);
            order.setFrom_where(address_list_default2.getStr("address"));
            order.setTrade_type(1);
        }
        order.setTrade_status(0);
        JSONArray ja = new JSONArray();
        ja.add(new Date().getTime());
        order.setTrade_status_log(JSONUtil.toJsonStr(ja));
        orderService.save(order);
        return ResponseEntity.ok("您已下单,订单已生成");
    }



    @PostMapping("/get_order")
    @ApiOperation(value = "传入类型为字符串,内含token,ordernum")
    public ResponseEntity<?> get_order(@RequestBody String body) throws IOException {
        //@RequestParam String token,@RequestParam String ordernum
        JSONObject obj = (JSONObject) JSONUtil.parse(body);
        String token = obj.getStr("token");
        String ordernum = obj.getStr("ordernum");
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        Order o = orderService.getOrderByOrderNum(ordernum);
        if(o==null){
            return ResponseEntity.ok("订单不存在!");
        }
        JSONObject result = (JSONObject) JSONUtil.parse(o);
        if(result.getStr("trade_status_log").equalsIgnoreCase("")){
            result.set("trade_status_log",new JSONArray());
        }else{
            result.set("trade_status_log",JSONUtil.parse(result.getStr("trade_status_log")));
        }
        if(o.getCollect_way()!=null && !o.getCollect_way().equalsIgnoreCase("")){
            JSONArray ja = JSONUtil.parseArray(o.getCollect_way());
            result.set("collect_way",ja);
        }

        UserShop us = userShopService.getEntityByUid(o.getProductBuyerUid());

        User seller = userService.getUserByUId(o.getProductSellerUid());
        seller.setPassword("****");
        User buyer = userService.getUserByUId(o.getProductBuyerUid());
        buyer.setPassword("****");
        result.set("shop",us);
        result.set("seller",seller);
        result.set("buyer",buyer);
        return ResponseEntity.ok(result);
    }


    @GetMapping("/get_all_buyer_orders")
    @ApiOperation(value = "传入类型为字符串,内含token,获取所有相关的订单")
    public ResponseEntity<?> get_all_buyer_orders(@RequestParam String token) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
       List<Order> list =  orderService.getAllBuysByUserID(u.getUid());

        JSONArray ja = new JSONArray();
        for(int i =0;i<list.size();i++){
            JSONObject obj = (JSONObject) JSONUtil.parse( list.get(i));
            User seller = userService.getUserByUId(list.get(i).getProductSellerUid());
            seller.setPassword("****");
            User buyer = userService.getUserByUId(list.get(i).getProductBuyerUid());
            buyer.setPassword("****");
            obj.set("buyer",buyer);
            obj.set("seller",seller);
            ja.add(obj);
        }
        return ResponseEntity.ok(ja);
    }


    @GetMapping("/get_all_seller_orders")
    @ApiOperation(value = "传入类型为字符串,内含token,获取所有相关的订单")
    public ResponseEntity<?> get_all_seller_orders(@RequestParam String token) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        List<Order> list =  orderService.getAllSellsByUserID(u.getUid());
        JSONArray ja = new JSONArray();
        for(int i =0;i<list.size();i++){
            JSONObject obj = (JSONObject) JSONUtil.parse( list.get(i));
            User seller = userService.getUserByUId(list.get(i).getProductSellerUid());
            seller.setPassword("****");
            User buyer = userService.getUserByUId(list.get(i).getProductBuyerUid());
            buyer.setPassword("****");
            obj.set("buyer",buyer);
            obj.set("seller",seller);
            ja.add(obj);
        }
        return ResponseEntity.ok(ja);
    }

//0代表下单,1表示农户开始配送,2代表企业签收,3代表订单完结（企业完成回收去向统计）
    @GetMapping("/farmer_send")
    @ApiOperation(value = "传入类型为字符串,内含token,获取所有相关的订单,此接口请自送上门的农户使用（农户主动)")
    public ResponseEntity<?> farmer_send(@RequestParam String token,@RequestParam String ordernum) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        if(u.getPosition()!=0){
            return ResponseEntity.ok("此接口为农户使用,你无权使用!");
        }
        Order o = orderService.getOrderByOrderNum(ordernum);
        if(o==null){
            return ResponseEntity.ok("订单不存在!");
        }

        boolean is_mine = false;
        List<Order> list_relate_with_me = orderService.getAllSellsByUserID(u.getUid());
        for(int i =0;i<list_relate_with_me.size();i++){
            if(list_relate_with_me.get(i).getOrderNumber().equalsIgnoreCase(ordernum)){
                is_mine=true;
                break;
            }
        }

        if(is_mine==false){
            return ResponseEntity.ok("此订单与你无关!");
        }

        if(o.getTrade_status()!=0){
            return ResponseEntity.ok("订单状态异常,可能跳过了订单过程!");
        }
        o.setTrade_status(1);


        JSONArray status_log=null;
        if(o.getTrade_status_log() == null || o.getTrade_status_log().equalsIgnoreCase("") || o.getTrade_status_log().equalsIgnoreCase("[]")){
            status_log=new JSONArray();
        }else{
            status_log = JSONUtil.parseArray(o.getTrade_status_log());
        }
        status_log.add(new Date().getTime());
        o.setTrade_status_log(JSONUtil.toJsonStr(status_log));


        orderService.save(o);
        return ResponseEntity.ok("success");
    }

    @GetMapping("/buyer_confirm")
    @ApiOperation(value = "传入类型为字符串,内含token,获取所有相关的订单")
    public ResponseEntity<?> buyer_confirm(@RequestParam String token,@RequestParam String ordernum) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        if(u.getPosition()==0){
            return ResponseEntity.ok("此接口为企业使用,你无权使用!");
        }
        Order o = orderService.getOrderByOrderNum(ordernum);
        if(o==null){
            return ResponseEntity.ok("订单不存在!");
        }
        List<Order> list_relate_with_me = orderService.getAllBuysByUserID(u.getUid());
        boolean is_mine = false;
        for(int i =0;i<list_relate_with_me.size();i++){
            if(list_relate_with_me.get(i).getOrderNumber().equalsIgnoreCase(ordernum)){
                is_mine=true;
                break;
            }
        }
        if(is_mine==false){
            return ResponseEntity.ok("此订单与你无关!");
        }
        if(o.getTrade_status()!=1){
            return ResponseEntity.ok("订单状态异常!,可能跳过了订单过程!");
        }
        o.setTrade_status(2);


        JSONArray status_log=null;
        if(o.getTrade_status_log() == null || o.getTrade_status_log().equalsIgnoreCase("") || o.getTrade_status_log().equalsIgnoreCase("[]")){
            status_log=new JSONArray();
        }else{
            status_log = JSONUtil.parseArray(o.getTrade_status_log());
        }
        status_log.add(new Date().getTime());
        o.setTrade_status_log(JSONUtil.toJsonStr(status_log));

        orderService.save(o);
        return ResponseEntity.ok("success");
    }








//企业上门

    @GetMapping("/buyer_send")
    @ApiOperation(value = "传入类型为字符串,内含token,获取所有相关的订单,此接口为自己上门收秸秆的企业使用（企业主动)")
    public ResponseEntity<?> buyer_send(@RequestParam String token,@RequestParam String ordernum) throws IOException {
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        if(u.getPosition()==0){
            return ResponseEntity.ok("此接口为企业使用,你无权使用!");
        }
        Order o = orderService.getOrderByOrderNum(ordernum);
        if(o==null){
            return ResponseEntity.ok("订单不存在!");
        }

        boolean is_mine = false;

        List<Order> list_relate_with_me = orderService.getAllBuysByUserID(u.getUid());
        for(int i =0;i<list_relate_with_me.size();i++){
            if(list_relate_with_me.get(i).getOrderNumber().equalsIgnoreCase(ordernum)){
                is_mine=true;
                break;
            }
        }

        if(is_mine==false){
            return ResponseEntity.ok("此订单与你无关!");
        }

        if(o.getTrade_status()!=0){
            return ResponseEntity.ok("订单状态异常,可能跳过了订单过程!");
        }
        o.setTrade_status(1);

        JSONArray status_log=null;
        if(o.getTrade_status_log() == null || o.getTrade_status_log().equalsIgnoreCase("") || o.getTrade_status_log().equalsIgnoreCase("[]")){
            status_log=new JSONArray();
        }else{
            status_log = JSONUtil.parseArray(o.getTrade_status_log());
        }
        status_log.add(new Date().getTime());
        o.setTrade_status_log(JSONUtil.toJsonStr(status_log));


        orderService.save(o);
        return ResponseEntity.ok("success");
    }

//企业回收去向

    @PostMapping("/buyer_collect")
    @ApiOperation(value = "传入类型为字符串,内含token,订单号ordernum,collect回收去向")
    public ResponseEntity<?> buyer_send(@RequestBody String body) throws IOException {
        JSONObject obj = (JSONObject) JSONUtil.parse(body);
        String token = obj.getStr("token");
        String ordernum = obj.getStr("ordernum");
        String collectway = obj.getStr("collectway");
        User u = userService.getUserByToken(token);
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }
        if(u.getPosition()==0){
            return ResponseEntity.ok("此接口为企业使用,你无权使用!");
        }
        Order o = orderService.getOrderByOrderNum(ordernum);
        if(o==null){
            return ResponseEntity.ok("订单不存在!");
        }

        boolean is_mine = false;
        List<Order> list_relate_with_me = orderService.getAllBuysByUserID(u.getUid());
        for(int i =0;i<list_relate_with_me.size();i++){
            if(list_relate_with_me.get(i).getOrderNumber().equalsIgnoreCase(ordernum)){
                is_mine=true;
                break;
            }
        }

        if(is_mine==false){
            return ResponseEntity.ok("此订单与你无关!");
        }

        if(o.getTrade_status()!=2){
            return ResponseEntity.ok("订单状态异常,可能跳过了订单过程!");
        }







        o.setTrade_status(3);


        JSONArray status_log=null;
        if(o.getTrade_status_log() == null || o.getTrade_status_log().equalsIgnoreCase("") || o.getTrade_status_log().equalsIgnoreCase("[]")){
            status_log=new JSONArray();
        }else{
            status_log = JSONUtil.parseArray(o.getTrade_status_log());
        }
        status_log.add(new Date().getTime());
        o.setTrade_status_log(JSONUtil.toJsonStr(status_log));


        o.setCollect_way(collectway);
        orderService.save(o);


        UserShop ushop = userShopService.getEntityByUid(u.getUid());
        ushop.setHas_get(ushop.getHas_get()+o.getProduct_amount());
        userShopService.save(ushop);

        return ResponseEntity.ok("success");
    }





}
